/*
 * OREKIT-X
 * Copyright 2002-2008 CS Communication & Systemes
 * 
 * Parts of this software package have been licensed to CS
 * Communication & Systemes (CS) under one or more contributor license
 * agreements.  See the NOTICE file distributed with this work for
 * additional information.
 *  
 * This is an experimental copy of OREKIT from www.orekit.org.
 * Please use the original OREKIT from orekit.org for normal work
 * unrelated to this research project.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you
 * may not use this file except in compliance with the License.  You
 * may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
 * implied.  See the License for the specific language governing
 * permissions and limitations under the License.
 */
package ore.forces.gravity;

import org.apache.commons.math.geometry.Vector3D;

import ore.CelestialBody;
import ore.ForceModel;
import ore.SpacecraftState;
import ore.errors.OrekitException;
import ore.propagation.events.EventDetector;
import ore.propagation.numerical.TimeDerivativesEquations;


/**
 * Third body attraction force model.
 *
 * @author Fabien Maussion
 * @author V&eacute;ronique Pommier-Maurussane
 */
public class ThirdBodyAttraction
    extends Object
    implements ForceModel
{

    private final CelestialBody body;


    /** 
     * @param body The third body (e.g. Sun or Moon)
     */
    public ThirdBodyAttraction(CelestialBody body) {
        super();
        this.body = body;
    }


    /** {@inheritDoc}
     */
    public void addContribution(final SpacecraftState s, final TimeDerivativesEquations adder)
        throws OrekitException
    {
        /*
         * Compute bodies separation vectors and squared norm
         */
        final Vector3D centralToBody = body.getPositionVelocity(s.getDate(), s.getFrame()).getPosition();
        final double r2Central       = Vector3D.dotProduct(centralToBody, centralToBody);
        final Vector3D satToBody     = centralToBody.subtract(s.getPositionVelocity().getPosition());
        final double r2Sat           = Vector3D.dotProduct(satToBody, satToBody);
        /*
         * Compute relative acceleration
         */
        final Vector3D gamma =
            new Vector3D(body.getGM() * Math.pow(r2Sat, -1.5), satToBody,
                        -body.getGM() * Math.pow(r2Central, -1.5), centralToBody);

        /*
         * Add contribution to the ODE second member
         */
        adder.addXYZAcceleration(gamma.getX(), gamma.getY(), gamma.getZ());
    }

    /** {@inheritDoc}
     */
    public EventDetector[] getEventsDetectors() {
        return new EventDetector[0];
    }
}
